<?php

namespace Beerus\Modules\Peanut\Controllers;


use App\Http\Controllers\Controller;
use App\Pockets\GridDataModel as pGridDataModel;
use Biz\pockets\excel\DownExcel;
use Biz\tools\helper\Common;
use Doraemon\cache\UserNick;
use Doraemon\model\Peanut\DesignerRIDModel;
use Doraemon\model\Peanut\RakeBackModel;
use Doraemon\model\Peanut\RakeBackRecordModel;
use Doraemon\service\Member\MemberService;
use Doraemon\service\Peanut\RakeBackService;
use Doraemon\service\User;
use Doraemon\tools\Log;
use Encore\Admin\Facades\Admin;
use Encore\Admin\Grid;
use Encore\Admin\Grid\Displayers\DropdownActions;
use Encore\Admin\Layout\Content;
use Encore\Admin\Widgets\Form;
use Illuminate\Http\Request;
use Illuminate\Support\MessageBag;

/**
 * 带货设计师Controller
 */
class DesignerController extends Controller
{

    /**
     * 带货设计师列表
     *
     * @param Content $content
     * @param Request $request
     * @return void
     */
    public function index(Content $content, Request $request) {
        $page = $request->input('page', 1);
        $pageSize = $request->input('per_page', 10);
        $limit = [($page - 1) * $pageSize, $pageSize];

        $find = $request->input('Find', '');
        $findGroup = $request->input('Find_group', 0);


        $where = [];
        if (!empty($find)) {
            switch ($findGroup) {
                case 0:$where['uid'] = $find;break;
                case 1:{
                    $uid = User::getUidByNick($find);
                    if ($uid) {
                        $where['uid'] = $uid;
                    }
                } break;
                case 2:$where['relation_id'] = $find;break;

            }
        }

        $list = DesignerRIDModel::getList($where, $limit);


        $options = array(
            "currentPage" => $page,
            "perPage" => $pageSize,
        );


        $gridModel = new pGridDataModel($list['list'], $list['total'], $options);

        $grid = Admin::grid($gridModel,
            function (Grid $grid)use($pageSize) {
                $grid->paginate($pageSize);
                $grid->filter(function (Grid\Filter $filter) {
                    $filter->disableIdFilter();
                    $filter->column(1/2, function ($filter) {
                        $filter->group('Find', function ($group) {
                            $group->equal('设计师uid');
                            $group->equal('设计师昵称');
                            $group->equal('阿里妈妈RID');
                        });
                    });
                    $filter->expand();
                });


                $grid->disableExport();
                $grid->disableRowSelector();
                // $grid->disableCreateButton();
                //$grid->disableActions();

                $grid->column('uid', '用户UID');
                $grid->column('user_nick', '设计师昵称')->display(function () {
                    return UserNick::uid2nick($this->uid);
                });

                $grid->column('relation_id', '阿里妈妈RID');


            }
        );

        return $content
            ->header('带货设计师管理')
            ->breadcrumb(['text' => '设计师带货'])
            ->row($grid)
            ;
    }

    /**
     * 编辑或者新增带货设计师
     * @param Request $request request
     * @param Content $content content
     * @param int $id id
     * @return Content
     */
    public function edit(Request $request, Content $content, $id = 0) {
        $request = $request->all();

        if (!$id) {
            $isCreate = true;
            $header = '新增';
        } else {
            $isCreate = false;
            $header = '修改';
        }


        return $content->header('新增')
            ->description(' ')
            ->breadcrumb(
                ['text' => '带货设计师管理', 'url' => '/Peanut/designer/list'],
                ['text' => '新增带货设计师']
            )->row(self::editAction($request, $id, $isCreate));
    }

    public function editAction($request, $id = 0, $isCreate = false)
    {
        $data = [];
        if (!$isCreate) {
            $data = DesignerRIDModel::get('*', ['id' => $id]);
        }

        $form = new Form($data);
        $form->hidden('id');
        $form->confirm('确定保存吗？');
        $form->action('/admin/Peanut/designer/save');

        $form->text('uid', '用户UID')
            ->setWidth(4, 2)
            ->required();
        $form->text('relation_id', '阿里妈妈RID')
            ->setWidth(4, 2)
            ->required();
        return $form->render();
    }

    /**
     * 新增或者编辑保存
     * @param Request $request
     * @return Application|RedirectResponse|Redirector
     */
    public function save(Request $request)
    {
        try { //统一错误提示
            $params = $request->all();
            //校验参数
            $res_msg = Common::validatorRule([
                "relation_id" => 'required',
                "uid" => 'required|integer'
            ], $params);
            if (true !== $res_msg) { //校验失败
                throw new \Exception($res_msg);
            }

            $id = $params['id']; //数据id

            $uid = $params['uid']; //设计师uid
            $relationId = $params['relation_id'];//阿里妈妈RID


            //判断uid是否是设计师
            if(!MemberService::isDesigner($params['uid'])) {
                throw new \Exception('该UID不是设计师');
            }

            //判断设计师uid和RID的关系是否存在， 已删除的
            $item = DesignerRIDModel::getOne([
                'relation_id' => $relationId,
                'uid' => $uid,
                'data_status' => DesignerRIDModel::STATUS_DELETE
            ], ['data_status', 'id']);

            if (!empty($id)) { //编辑
                //判断uid是否关联过设计师, 排除当前id
                if(!empty(DesignerRIDModel::getOne(['uid' => $uid, 'id[!]' => $id], 'id'))) {
                    throw new \Exception('该UID已存在列表中');
                }

                //判断RID是否绑定过设计师，排除当前id
                if(!empty(DesignerRIDModel::getOne(['relation_id' => $relationId, 'id[!]' => $id], 'id'))) {
                    throw new \Exception('该RID已与其他用户绑定');
                }

                if(!empty($item)) { //存在， 直接更新状态
                    if ($item['id'] != $id) { //已删除的数据
                        //更新已删除的为正常数据
                        DesignerRIDModel::updateData($item['id'], ['data_status' => DesignerRIDModel::STATUS_NORMAL]);
                        //更新提交的id为删除状态
                        DesignerRIDModel::updateData($id, ['data_status' => DesignerRIDModel::STATUS_DELETE]);
                    }


                } else {
                    DesignerRIDModel::updateData($id, [
                        'uid' => $uid,
                        'relation_id' => $relationId
                    ]);
                }
                $success = new MessageBag([
                    'title' => '更新成功',
                ]);

            } else {
                //判断uid是否关联过设计师
                if(!empty(DesignerRIDModel::getOne(['uid' => $uid], 'id'))) {
                    throw new \Exception('该UID已存在列表中');
                }

                //判断RID是否绑定过设计师
                if(!empty(DesignerRIDModel::getOne(['relation_id' => $relationId], 'id'))) {
                    throw new \Exception('该RID已与其他用户绑定');
                }
                if(!empty($item)) { //存在， 直接更新状态
                    DesignerRIDModel::updateData($item['id'], ['data_status' => DesignerRIDModel::STATUS_NORMAL]);
                    $success = new MessageBag([
                        'title' => '更新成功',
                    ]);
                    return redirect('/admin/Peanut/designer/list')->with(compact('success'));
                }

                DesignerRIDModel::insertData([
                    'uid' => $uid,
                    'relation_id' => $relationId
                ]);
                $success = new MessageBag([
                    'title' => '添加成功',
                ]);
            }

            return redirect('/admin/Peanut/designer/list')->with(compact('success'));



        } catch (\Exception $e) {
            $error = new MessageBag([
                'title' => $e->getMessage(),
            ]);
            return back()->with(compact('error'));
        }

    }


    /**
     * 删除带货设计师
     * @param Request $request
     * @param int $id
     * @return \Illuminate\Contracts\Foundation\Application|\Illuminate\Http\RedirectResponse|\Illuminate\Routing\Redirector|void
     */
    public function del(Request $request, $id = 0)
    {
        try {
            if(empty($id)) {
                throw new \Exception('id不存在');
            }
            DesignerRIDModel::updateData($id, ['data_status' => DesignerRIDModel::STATUS_DELETE]);
            return redirect(url('/admin/Peanut/designer/list'))->with(compact('success'));
        } catch (\Exception $e) {
            Log::debug($e->getMessage());
            $error = new MessageBag([
                'title' => '删除失败,信息:' . $e->getMessage()
            ]);
            return back()->with(compact('error'));
        }
    }

}